import type { Router } from 'vue-router'
import { useUserStore } from '@/store'
import router from '@/router'
// import 'vite/dynamic-import-polyfill'

export const useSetRouter = (router: Router) => {
  const userStore = useUserStore()
  router.beforeEach(async (to) => {
    await loadDynamicRoutes(userStore)
  })
}
const pages = import.meta.glob('../../views/**/*.vue')
// 动态加载组件
const loadComponent = (view) => {
  return pages[`../../${view}`]
}

// 递归处理路由配置中的组件路径
const processRoutes = (routes) => {
  routes.forEach((route) => {
    if (route.component) {
      route.component = loadComponent(route.component)
    }
    if (route.children) {
      processRoutes(route.children)
    }
  })
}

// 获取动态路由
const loadDynamicRoutes = async (userStore) => {
  const routerList = userStore.getRouterList
  if (routerList === undefined) return
  let clone = JSON.parse(JSON.stringify(routerList))
  clone = setRouterTree(clone)
  const dynamicRoutes = clone
  // 处理动态路由中的组件路径
  processRoutes(dynamicRoutes)

  // 添加动态路由到路由实例中
  dynamicRoutes.forEach((route) => {
    router.addRoute(route)
  })
  console.log('router.getRoutes()',router.getRoutes())
  return {}
}

type RouterType = {
  path: string
  name: string
  component: string
  children?: Array<RouterType>
}
//处理数据
const setRouterTree = (arr) => {
  let obj = []
  if (Array.isArray(arr) && arr.length > 0) {
    obj = arr.map((i) => {
      const redirect = {}
      if (i?.redirect) {
        redirect.name = i.redirect
        return {
          path: i.path,
          name: i.frontEndPerms,
          component: i.component,
          meta: {
            name: i.label
          },
          redirect,
          children: setRouterTree(i.children)
        }
      }
      return {
        path: i.path,
        name: i.frontEndPerms,
        component: i.component,
        meta: {
          name: i.label
        },
        children: setRouterTree(i.children)
      }
    })
  }
  return obj
}

